package com.pptree.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("*.do")
public class CoreServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
   
	protected void delete(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------------------>>>delete");
    }

	protected void query(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------------------>>>query");
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------------------>>>add");

    }
    
    
    protected void save(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("------------------>>>save");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取方法名字
        String servletPath = request.getServletPath();
        System.out.println("servletPath------->" + servletPath);
        // 去掉斜杠和.do
        String methodName = servletPath.substring(1, servletPath.length() - 3);
        System.out.println("methodName---->" + methodName);
        
        try {
            // 利用反射获取方法
            Method method = getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            // 执行相应的方法
            method.invoke(this, request, response);
        }
        catch(NoSuchMethodException e){
        	 e.printStackTrace();
        	 throw new RuntimeException("没有找到"+methodName+"方法，请检查该方法是否存在！");  
        } 
        catch (Exception e) {
        	 e.printStackTrace();
        	 throw new RuntimeException("你调用的方法"+methodName+",内部发生了异常！");
        }
	}

}
 